package org.example.volunteerend.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.example.volunteerend.common.Result;
import org.example.volunteerend.dto.PageResponse;
import org.example.volunteerend.dto.ProjectCreateRequest;
import org.example.volunteerend.entity.ProjectCategory;
import org.example.volunteerend.entity.User;
import org.example.volunteerend.entity.VolunteerProject;
import org.example.volunteerend.service.ProjectService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class ProjectController {

    private final ProjectService projectService;

    /**
     * 获取项目分类列表
     */
    @GetMapping("/project-categories")
    public Result<List<Map<String, Object>>> getProjectCategories() {
        List<ProjectCategory> categories = projectService.getAllCategories();
        
        // 转换为符合规范的响应格式
        List<Map<String, Object>> formattedCategories = categories.stream().map(category -> {
            Map<String, Object> item = new HashMap<>();
            item.put("category_id", category.getCategoryId());
            item.put("category_name", category.getCategoryName());
            item.put("description", category.getDescription());
            item.put("icon_url", category.getIconUrl());
            return item;
        }).collect(Collectors.toList());
        
        return Result.success(formattedCategories);
    }

    /**
     * 项目列表查询
     */
    @GetMapping("/projects")
    public Result<Map<String, Object>> getProjects(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder) {
        
        PageResponse<VolunteerProject> pageResponse = projectService.getProjectList(
                page, pageSize, keyword, categoryId, status, startTime, endTime, location, sortBy, sortOrder);
        
        // 转换为符合规范的响应格式
        List<Map<String, Object>> rows = pageResponse.getRecords().stream().map(project -> {
            Map<String, Object> item = new HashMap<>();
            item.put("project_id", project.getProjectId());
            item.put("project_name", project.getProjectName());
            item.put("description", project.getDescription());
            item.put("start_time", project.getStartTime() != null ? project.getStartTime().toString() : null);
            item.put("end_time", project.getEndTime() != null ? project.getEndTime().toString() : null);
            item.put("location", project.getLocation());
            item.put("max_volunteers", project.getMaxVolunteers());
            item.put("current_volunteers", project.getCurrentVolunteers());
            item.put("status", project.getStatus());
            item.put("cover_image_url", project.getCoverImageUrl());
            item.put("likes", project.getLikes());
            
            // 转换分类信息
            if (project.getCategories() != null) {
                List<Map<String, Object>> categories = project.getCategories().stream().map(category -> {
                    Map<String, Object> categoryMap = new HashMap<>();
                    categoryMap.put("category_id", category.getCategoryId());
                    categoryMap.put("category_name", category.getCategoryName());
                    return categoryMap;
                }).collect(Collectors.toList());
                item.put("categories", categories);
            }
            
            return item;
        }).collect(Collectors.toList());
        
        Map<String, Object> data = new HashMap<>();
        data.put("total", pageResponse.getTotal());
        data.put("rows", rows);
        
        return Result.success(data);
    }

    /**
     * 获取项目详情
     */
    @GetMapping("/projects/{projectId}")
    public Result<Map<String, Object>> getProjectDetail(@PathVariable Integer projectId) {
        VolunteerProject project = projectService.getProjectDetail(projectId);
        
        if (project == null) {
            return Result.error("项目不存在");
        }
        
        // 转换为符合规范的响应格式
        Map<String, Object> data = new HashMap<>();
        data.put("project_id", project.getProjectId());
        data.put("project_name", project.getProjectName());
        data.put("description", project.getDescription());
        data.put("start_time", project.getStartTime() != null ? project.getStartTime().toString() : null);
        data.put("end_time", project.getEndTime() != null ? project.getEndTime().toString() : null);
        data.put("location", project.getLocation());
        data.put("max_volunteers", project.getMaxVolunteers());
        data.put("current_volunteers", project.getCurrentVolunteers());
        data.put("status", project.getStatus());
        data.put("cover_image_url", project.getCoverImageUrl());
        data.put("project_images", project.getProjectImages());
        data.put("likes", project.getLikes());
        data.put("dislikes", project.getDislikes());
        
        // 转换分类信息
        if (project.getCategories() != null) {
            List<Map<String, Object>> categories = project.getCategories().stream().map(category -> {
                Map<String, Object> categoryMap = new HashMap<>();
                categoryMap.put("category_id", category.getCategoryId());
                categoryMap.put("category_name", category.getCategoryName());
                return categoryMap;
            }).collect(Collectors.toList());
            data.put("categories", categories);
        }
        
        // 转换组织者信息
        if (project.getOrganizer() != null) {
            Map<String, Object> organizer = new HashMap<>();
            User organizerUser = project.getOrganizer();
            organizer.put("user_id", organizerUser.getUserId());
            organizer.put("username", organizerUser.getUsername());
            organizer.put("real_name", organizerUser.getRealName());
            data.put("organizer", organizer);
        }
        
        // 转换志愿者列表
        if (project.getVolunteers() != null) {
            List<Map<String, Object>> volunteers = project.getVolunteers().stream().map(volunteer -> {
                Map<String, Object> volunteerMap = new HashMap<>();
                volunteerMap.put("user_id", volunteer.getUserId());
                volunteerMap.put("username", volunteer.getUsername());
                volunteerMap.put("avatar_url", volunteer.getAvatarUrl());
                return volunteerMap;
            }).collect(Collectors.toList());
            data.put("volunteers", volunteers);
        }
        
        return Result.success(data);
    }
    
    /**
     * 发布志愿项目
     */
    @PostMapping("/projects")
    public Result<Map<String, Object>> createProject(@RequestBody ProjectCreateRequest request, HttpServletRequest httpRequest) {
        // 获取当前登录用户ID
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        try {
            // 创建项目
            Integer projectId = projectService.createProject(request, userId);
            
            // 返回成功信息
            Map<String, Object> data = new HashMap<>();
            data.put("project_id", projectId);
            
            return Result.success("项目发布成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("项目发布失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新项目封面
     */
    @PostMapping("/projects/{projectId}/cover")
    public Result<Map<String, Object>> updateProjectCover(
            @PathVariable Integer projectId,
            @RequestParam("cover") MultipartFile coverFile) {
        try {
            // 更新项目封面
            String coverUrl = projectService.updateProjectCover(projectId, coverFile);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("cover_image_url", coverUrl);
            
            return Result.success("封面图片更新成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("封面图片更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传项目图片
     */
    @PostMapping("/projects/{projectId}/images")
    public Result<Map<String, Object>> uploadProjectImages(
            @PathVariable Integer projectId,
            @RequestParam("images") List<MultipartFile> imageFiles) {
        try {
            // 上传项目图片
            List<String> imageUrls = projectService.uploadProjectImages(projectId, imageFiles);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("image_urls", imageUrls);
            
            return Result.success("图片上传成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("图片上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 项目报名
     */
    @PostMapping("/projects/{projectId}/register")
    public Result<Map<String, Object>> registerProject(
            @PathVariable Integer projectId,
            HttpServletRequest httpRequest) {
        
        // 打印详细的debug信息
        System.out.println("\n=== 项目报名接口 ===");
        System.out.println("报名项目ID: " + projectId);
        System.out.println("请求URI: " + httpRequest.getRequestURI());
        System.out.println("请求方法: " + httpRequest.getMethod());
        
        // 打印所有请求头
        java.util.Enumeration<String> headerNames = httpRequest.getHeaderNames();
        System.out.println("--- 请求头 ---");
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + httpRequest.getHeader(headerName));
        }
        
        // 尝试从不同头中获取token
        String authHeader = httpRequest.getHeader("Authorization");
        String tokenHeader = httpRequest.getHeader("token");
        System.out.println("Authorization头: " + authHeader);
        System.out.println("token头: " + tokenHeader);
        
        // 从token中获取用户ID
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        System.out.println("从token中获取的用户ID: " + userId);
        
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        try {
            Integer registrationId = projectService.registerProject(projectId, userId);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("registration_id", registrationId);
            
            return Result.success("报名成功", data);
        } catch (IllegalArgumentException e) {
            System.out.println("报名参数错误: " + e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            System.out.println("报名异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("报名失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消项目报名
     */
    @DeleteMapping("/projects/{projectId}/register")
    public Result<Object> cancelRegistration(
            @PathVariable Integer projectId,
            HttpServletRequest httpRequest) {
        
        // 打印debug信息
        System.out.println("取消报名项目ID: " + projectId);
        System.out.println("Authorization: " + httpRequest.getHeader("Authorization"));
        System.out.println("token: " + httpRequest.getHeader("token"));
        
        // 从token中获取用户ID
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        System.out.println("从token中获取的用户ID: " + userId);
        
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        try {
            projectService.cancelRegistration(projectId, userId);
            return Result.success("取消报名成功", null);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("取消报名失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取项目报名列表
     */
    @GetMapping("/projects/{projectId}/registrations")
    public Result<Map<String, Object>> getProjectRegistrations(
            @PathVariable Integer projectId,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String status) {
        
        try {
            PageResponse<?> pageResponse = projectService.getProjectRegistrations(
                    projectId, page, pageSize, status);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("total", pageResponse.getTotal());
            data.put("rows", pageResponse.getRecords());
            
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取报名列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新项目状态
     */
    @PutMapping("/projects/{projectId}/status")
    public Result<Object> updateProjectStatus(
            @PathVariable Integer projectId,
            @RequestBody Map<String, String> requestBody) {
        
        String status = requestBody.get("status");
        if (status == null || status.isEmpty()) {
            return Result.error("状态不能为空");
        }
        
        try {
            projectService.updateProjectStatus(projectId, status);
            return Result.success("项目状态更新成功", null);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新项目状态失败：" + e.getMessage());
        }
    }
} 